package com.heatup.apt.management.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heatup.apt.common.constants.UserConstants;
import com.heatup.apt.common.dao.SmsLogMapper;
import com.heatup.apt.common.dao.store.StoreInfoMapper;
import com.heatup.apt.common.util.CheckCodeUtil;
import com.heatup.apt.common.util.RequestTools;
import com.heatup.apt.common.util.SmsUtil;
import com.heatup.apt.management.service.coupon.CouponService;
import com.heatup.apt.management.util.GenerateShortUrlUtil;
import com.heatup.apt.management.util.ManageConfigPropertiesUtil;
import com.heatup.apt.model.SmsLog;
import com.heatup.apt.model.coupon.CouponInfo;
import com.heatup.apt.model.store.StoreInfo;

/**
 *
 * 优惠券模块后台控制类
 * @author: Blank
 * @create: 2016-11-25-上午 9:55
 */
@Controller
@RequestMapping(value = "/system/coupon")
public class CouponController extends BaseController {

    @Autowired
    CouponService couponService;

    @Autowired
    private SmsLogMapper smsLogMapper;
    @Autowired
    private StoreInfoMapper storeInfoMapper;

    private static final Logger log = LoggerFactory.getLogger(CouponController.class);


    /**
     * 优惠券领取记录页面
     *
     * @return
     */
    @RequestMapping(value = "/to_get_list")
    public ModelAndView toCouponGetHistory(@RequestParam(required = false) Integer couponId){
        ModelAndView modelAndView = new ModelAndView("coupon/coupon_get_list");
        if (couponId !=null)
            modelAndView.addObject("couponId", couponId);
        return modelAndView;
    }


    /**
     * 优惠券领取记录分页
     *
     * @param pageIndex 页码
     * @param pageSize 页面大小
     * @param couponId 优惠券ID
     * @param userId 用户ID
     * @return
     */
    @RequestMapping(value = "/coupon_get_list")
    public void couponGetHistory(HttpServletResponse response, @RequestParam int pageIndex,
                                   @RequestParam int pageSize,
                                   @RequestParam Integer couponId,
                                   Integer userId){

        if (pageIndex > 0)
            --pageIndex;
        if (pageSize <=0)
            pageSize = 10;
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("pageIndex", pageIndex);
        paramsMap.put("pageSize", pageSize);
        paramsMap.put("couponId", couponId);
        paramsMap.put("userId", userId);

        JSONObject jsonObject = new JSONObject();

        Map<String, Object> map = couponService.queryCouponGetHistoryList(paramsMap);

        jsonObject.put("couponDetailList", map.get("couponDetailList"));
        jsonObject.put("couponDetailCount", map.get("couponDetailCount"));
        jsonObject.put("couponGetCount", map.get("couponGetCount"));
        jsonObject.put("couponUsedCount", map.get("couponUsedCount"));

        responseSendMsg(response, jsonObject.toString());
    }



    /**
     * 下架优惠券
     *
     * @param id 主键
     * @return
     */
    @RequestMapping(value = "/offlineCoupon/{id}")
    @ResponseBody
    public String offlineCoupon(@PathVariable Integer id){
        int result = 0;

        try {
            result = couponService.updateCouponToOffline(id);

        } catch (Exception e) {
            log.error(e.getMessage() + e.toString());
        }
        if (result > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * 优惠券列表页面
     * @return
     */
    @RequestMapping(value = "/to_list")
    public ModelAndView to_list(){
        ModelAndView modelAndView = new ModelAndView("coupon/coupon_list");
        return modelAndView;
    }

    /**
     * 优惠券列表分页查询
     * @param response
     * @return
     */
    @RequestMapping(value = "/coupon_list", method = {RequestMethod.GET, RequestMethod.POST})
    public void couponList(HttpServletResponse response,
                               @RequestParam int pageIndex,
                               @RequestParam int pageSize,
                               @RequestParam(required = false) Integer id,
                               @RequestParam(required = false) Integer isLimitCourse,
                               @RequestParam(required = false) Integer couponStatus
                               ) {

        if (pageIndex > 0)
            --pageIndex;
        if (pageSize <=0)
            pageSize = 10;
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("pageIndex", pageIndex);
        paramsMap.put("pageSize", pageSize);
        paramsMap.put("id", id);
        paramsMap.put("isLimitCourse", isLimitCourse);
        paramsMap.put("couponStatus", couponStatus);

        Map<String, Object> map = couponService.queryCouponList(paramsMap);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("couponList", map.get("couponList"));
        jsonObject.put("couponCount", map.get("couponCount"));
        responseSendMsg(response, jsonObject.toString());
    }


    /**
     * 优惠券新增(审核)列表页面
     *
     * @return
     */
    @RequestMapping(value = "/to_add_list")
    public ModelAndView to_add_list(){
        ModelAndView modelAndView = new ModelAndView("coupon/coupon_add_list");
        return modelAndView;
    }

    /**
     * 优惠券新增(审核)分页
     *
     */
    @RequestMapping(value = "/add_list")
    public void couponCheckList(HttpServletResponse response,
                                @RequestParam int pageIndex,
                                @RequestParam int pageSize,
                                @RequestParam(required = false) Integer id
                                ){
        if (pageIndex > 0)
            --pageIndex;
        if (pageSize <=0)
            pageSize = 10;
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("pageIndex", pageIndex);
        paramsMap.put("pageSize", pageSize);
        paramsMap.put("id", id);

        Map<String, Object> map = couponService.queryCouponAddList(paramsMap);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("couponCheckList", map.get("couponCheckList"));
        jsonObject.put("couponCheckCount", map.get("couponCheckCount"));
        responseSendMsg(response, jsonObject.toString());
    }



    /**
     * 优惠券添加页面1
     * @return
     */
    @RequestMapping(value = "/to_add_step1")
    public ModelAndView to_coupon_add_step1(@RequestParam(required = false) Integer id){

        ModelAndView modelAndView = new ModelAndView("coupon/coupon_add_step1");
        CouponInfo couponInfo = null;
        if (id !=null){
            couponInfo = couponService.queryById(id);
            if (couponInfo != null) {
                modelAndView.addObject(couponInfo);
                modelAndView.addObject(JSON.toJSONString(couponInfo));
            }
        }
        List<StoreInfo> listS = storeInfoMapper.queryAllStoreList();
        modelAndView.addObject("storeList", JSON.toJSONString(listS));
        return modelAndView;
    }

    /**
     * 优惠券保存1
     * @return
     */
    @RequestMapping(value = "/save_coupon_add_step1")
    @ResponseBody
    public String save_coupon_add_step1(CouponInfo couponInfo){

        JSONObject resultJson = new JSONObject();
        resultJson.put("success", false);
        if (couponInfo != null) {
            try {
                //检查使用时间是否小于兑换时间 小于不允许保存
                if ( couponInfo.getChangeMode() != null && couponInfo.getChangeMode() == 2
                                && couponInfo.getUseMode() != null && couponInfo.getUseMode() == 2
                                && couponInfo.getUseBeginDate() != null && couponInfo.getChangeBeginDate() != null
                                && couponInfo.getUseBeginDate().before(couponInfo.getChangeBeginDate())) {
                    //有相同的不可保存
                    resultJson.put("msg", "优惠券的使用开始时间不可在兑换开始时间之前,请修改后再试");
                    return resultJson.toJSONString();
                }

                //检查是否存在相同的名称 兑换/使用时间相冲突的优惠券
                boolean check = couponService.checkByName(couponInfo);
                if (check) {
                    //有相同的不可保存
                    resultJson.put("msg", "存在名称相同且兑换时间/使用时间冲突的优惠券,请修改后再试");
                    return resultJson.toJSONString();
                }

                if (couponInfo.getCouponStatus() != null && couponInfo.getCouponStatus() == 2) {
                    //更新不审核
                    resultJson.put("go", "list");
                }
                couponService.saveCoupon(couponInfo, getUserInfo().getUserName());
                resultJson.put("success", true);
                resultJson.put("id", couponInfo.getId());
            } catch (Exception e) {
                log.error("优惠券保存step1 失败--->" + e.toString());
                resultJson.put("msg", "优惠券保存失败--->" + e.toString());
            }
        }
        return resultJson.toJSONString();
    }

    /**
     * 优惠券添加页面2
     * @return
     */
    @RequestMapping(value = "/to_coupon_add_step2/{id}")
    public ModelAndView to_coupon_add_step2(@PathVariable() Integer id){

        ModelAndView modelAndView = new ModelAndView("coupon/coupon_add_step2");
        modelAndView.addObject("id", id);
        modelAndView.addObject("checkList", couponService.queryAllCheckList(1));//优惠券校验人列表
        return modelAndView;
    }

    /**
     * 发送验证码
     *
     * @param mobile 手机号
     * @return
     */
    @RequestMapping(value = "/send")
    @ResponseBody
    private String send(@RequestParam String mobile) {
        Integer userId = getUserInfo().getId();

        //未登陆
        if(userId == null){
            return "用户未登陆";
        }

        try{
            //检查发送间隔
            Object lastSend = this.getSession(SESSION_KEY_CHECK_CODE_LAST_SEND);
            if(lastSend != null){
                long lastSendTime = (long)lastSend;
                long currentTime = System.currentTimeMillis();
                long seconds =  (currentTime - lastSendTime)/1000;
                if(seconds < UserConstants.SEND_CHECK_CODE_INTERVAL){
                    return "验证码发送太频繁";
                }
            }

            //检查后台管理员发送限额
            int todayMyCount = smsLogMapper.queryManagementSmsCountByMobileAndUserId(mobile, userId);
            if(todayMyCount > UserConstants.CHECK_CODE_MANAGEMENT_MAX_SEND_COUNT){
                return "已超过今天短信限额";
            }
            int checkCode = CheckCodeUtil.getCheckCode();
            boolean sendResult = SmsUtil.sendCheckCode(mobile, checkCode + "");

            //发送记录
            SmsLog smsLog = new SmsLog();
            smsLog.setMobile(mobile);
            smsLog.setCheckCode(checkCode + "");
            smsLog.setUserId(userId);
            smsLog.setSendTime(new Date());
            smsLog.setSendResult(sendResult?1:2);
            smsLog.setSendType(1);
            smsLogMapper.insertSelective(smsLog);

            this.setSession(SESSION_KEY_MOBILE, mobile);
            this.setSession(SESSION_KEY_CHECK_CODE, checkCode);
            this.setSession(SESSION_KEY_CHECK_CODE_LAST_SEND, System.currentTimeMillis());
            return "success";

        }catch(Exception e){
            return "系统错误" + e.getMessage();
        }
    }

    /**
     * 校验验证码
     *
     * @param checkCode 验证码
     * @param id 优惠券ID
     * @return
     */
    @RequestMapping(value = "/check")
    @ResponseBody
    private String checkCheckCode(@RequestParam String checkCode,
                                  @RequestParam Integer id,
                                  @RequestParam String checkName,
                                  @RequestParam String mobile) {

        Integer userId = getUserInfo().getId();

        //未登陆
        if(userId == null){
            return "未登陆";
        }

        try{
            //有效期验证
            Object syscode = this.getSession(SESSION_KEY_CHECK_CODE);
            Object lastSend = this.getSession(SESSION_KEY_CHECK_CODE_LAST_SEND);
            if(syscode==null || lastSend==null){

                return "无验证码";
            }

            long lastSendTime = (long)lastSend;
            long currentTime = System.currentTimeMillis();
            long seconds =  (currentTime - lastSendTime)/1000;
            if(seconds > UserConstants.CHECK_CODE_TIMEOUT){
                return "验证码已失效,请重新发送";
            }

            //验证码验证
            if(syscode.toString().length() > 0 && syscode.toString().equals(checkCode)){
                //验证成功 上架优惠券
                couponService.updateCouponToOnline(id, checkName, mobile);
                return "success";
            }else{
                return "验证码错误";
            }
        }catch(Exception e){
            return "系统错误" + e.getMessage();
        }
    }

    /**
     * 下载优惠券详情
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/coupon_detail_down")
    public String downloadCouponDetail(@RequestParam Integer id){
    	JSONObject jsonObject = new JSONObject();
		Map<String, Object> map = couponService.downAndGeneratorCouponDetailInfo(id);
		jsonObject.put("data", map);
		return jsonObject.toJSONString();
    }


	@ResponseBody
	@RequestMapping("/download_file")
	public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileName = RequestTools.RequestString(request, "fileName","");
		String baseDir= ManageConfigPropertiesUtil.getString("uploadImagDir");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
		File file = new File(baseDir + File.separator + fileName);
		FileInputStream fis = null;
		OutputStream ops = null;
		try {
			fis = new FileInputStream(file);
			HSSFWorkbook wb = new HSSFWorkbook(fis);
			ops = response.getOutputStream();
			wb.write(ops);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
				ops.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@ResponseBody
	@RequestMapping("/short_url")
	public String shortUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject resultJson = new JSONObject();
		String conponId = RequestTools.RequestString(request, "conponId","");
		String couponCodeUrl = ManageConfigPropertiesUtil.getString("coupon_code_qr_url");
		String coupon_code_url = couponCodeUrl.replace("{conponId}", conponId);
		String shor_coupon_url = GenerateShortUrlUtil.generateShortUrl(coupon_code_url);
		resultJson.put("data", shor_coupon_url);
		return resultJson.toJSONString();
	}
	
}
